import os
import json

from PyQt5.QtWidgets import QVBoxLayout, QDialog, QPushButton, QLabel, QLineEdit, QMessageBox, QTextEdit, QHBoxLayout

from PyQt5.QtCore import Qt

EMAIL_FOLDER_PATH = os.path.join("db")
EMAIL_FILE_PATH = os.path.join("db", 'email.json')


class EmailDialog(QDialog):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.filed_dict = {}
        self.init_filed_dict()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("邮箱配置")
        self.resize(300, 270)

        layout = QVBoxLayout()

        form_data_list = [
            {"title": "SMTP服务器:", "field": "smtp"},
            {"title": "发件箱:", "field": "from"},
            {"title": "密码:", "field": "pwd"},
            {"title": "收件人（多个用逗号分隔）:", "field": "to"},
        ]

        for item in form_data_list:
            layout.addWidget(QLabel(item['title']))

            field = item['field']
            txt = QLineEdit()
            if field in self.filed_dict:
                txt.setText(self.filed_dict[field])
            layout.addWidget(txt)

            self.filed_dict[field] = txt

        btn_save = QPushButton("保存")
        btn_save.clicked.connect(self.event_save_click)
        layout.addWidget(btn_save, 0, Qt.AlignRight)

        self.setLayout(layout)

    def event_save_click(self):
        # 1.获取输入值
        info = {}
        for filed, obj in self.filed_dict.items():
            info[filed] = obj.text().strip()

        # 2.保存
        if not os.path.exists(EMAIL_FOLDER_PATH):
            os.makedirs(EMAIL_FOLDER_PATH)

        with open(EMAIL_FILE_PATH, mode='w', encoding='utf-8') as f:
            json.dump(info, f, ensure_ascii=False)

        # 3.关闭窗口
        self.close()

    def init_filed_dict(self):
        if not os.path.exists(EMAIL_FILE_PATH):
            return
        with open(EMAIL_FILE_PATH, mode='r', encoding='utf-8') as f:
            self.filed_dict = json.load(f)



class LogDialog(QDialog):
    def __init__(self, sku_id, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sku_id = sku_id

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("日志记录")
        self.resize(500, 400)
        layout = QVBoxLayout()
        text_edit = QTextEdit()
        text_edit.setText("")

        layout.addWidget(text_edit)
        self.setLayout(layout)

        # 读取日志展示出来
        file_path = os.path.join("log", "{}.log".format(self.sku_id))
        if not os.path.exists(file_path):
            return

        with open(file_path, mode='r', encoding='utf-8') as f:
            content = f.read()
        text_edit.setText(content)
